package com.wdh.kjs.activity;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.NewsAdapter;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.PlatformNewsListModle;
import com.wdh.kjs.model.ShowNewsListForAppModle;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class NewsActivity extends BaseTopActivity {

    private PullToRefreshListView listView;
    private NewsAdapter newsAdapter;
    private List<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();
    private HashMap<String, String> maps = new HashMap<String, String>();
    public static int page = 1;
    public static int rows = 10;
    private ShowNewsListForAppModle showNewsListForAppModle;
    public static int totalrecords = 0;
    public boolean mLoading = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        page = 1;
        initview();
        intweb();
    }

    private void intweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Show_NewsList_For_App, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                showNewsListForAppModle = gson.fromJson(responseInfo.result, ShowNewsListForAppModle.class);
                if (showNewsListForAppModle.isSuccess()) {
                    //   totalrecords = showNewsListForAppModle.getTotalrecords();
                    //  totalrecords=5;
                    initwidge();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(NewsActivity.this, "网络异常！");
            }
        });

    }

    private void initview() {
        initTopBar("业内新闻");
        listView = (PullToRefreshListView) findViewById(R.id.news_listview);
    }

    private void initwidge() {
        newsAdapter = new NewsAdapter(this, initListViewData());
        listView.setAdapter(newsAdapter);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {


            // 下拉Pulling Down
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();
            }

            // 上拉Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项

                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();


            }

        });

    }

    private List<HashMap<String, String>> initListViewData() {
        datas = new ArrayList<>();
        ArrayList<PlatformNewsListModle> platformNewsListModles = showNewsListForAppModle.getPlatformNewsList();
        int size = platformNewsListModles.size();
        for (int i = 0; i < size; i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            PlatformNewsListModle platformNewsListModle = platformNewsListModles.get(i);
            hashMap.put("title", platformNewsListModle.getTitle());
            String time = getTime(platformNewsListModle.getCreatedTxStamp().toString().substring(0, 10));
            hashMap.put("time", time);
            hashMap.put("platformNewsId", platformNewsListModle.getPlatformNewsId());
            datas.add(hashMap);
        }
        totalrecords = datas.size();
        return datas;
    }

    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mLoading) {
                page += 1;
                try {
                    getMoreList();
                } catch (Exception e) {
                    page -= 1;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(NewsActivity.this, "已无更多数据！");
            listView.onRefreshComplete();
            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Show_NewsList_For_App, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                try {
                    showNewsListForAppModle = gson.fromJson(responseInfo.result, ShowNewsListForAppModle.class);
                    if (showNewsListForAppModle.isSuccess()) {
                        if (showNewsListForAppModle != null && showNewsListForAppModle.getPlatformNewsList().size() > 0) {
                            moreListViewData();
                        } else {
                            page -= 1;
                            ToastUtils.showShort(NewsActivity.this, "没有更多数据！");
                        }

                    }
                }catch (Exception e){
                    mLoading=false;
                    page -= 1;
                    ToastUtils.showShort(NewsActivity.this, "没有更多数据！");
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(NewsActivity.this, "网络异常！");
            }
        });

    }

    private void moreListViewData() {
        ArrayList<PlatformNewsListModle> platformNewsListModles = showNewsListForAppModle.getPlatformNewsList();
        int size = platformNewsListModles.size();
        for (int i = 0; i < size; i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            PlatformNewsListModle platformNewsListModle = platformNewsListModles.get(i);
            hashMap.put("title", platformNewsListModle.getTitle());
            String time = getTime(platformNewsListModle.getCreatedTxStamp().toString().substring(0, 10));
            hashMap.put("time", time);
            hashMap.put("platformNewsId", platformNewsListModle.getPlatformNewsId());
            datas.add(hashMap);
        }
        if (datas.size() == totalrecords) {
            mLoading = false;
        } else {
            totalrecords = datas.size();
        }
        if(mLoading==true) {
            newsAdapter.notifyDataSetChanged();
        }
    }

    private String getTime(String date_str) {
        String format = "yy/MM/dd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(date_str + "000")));
    }
}
